import java.io.*;

public class TerminalDemo {
    static String[] cmd = {"/bin/bash"};
//    static String[] cmd = {"cmd"};

    public static void main(String[] args) {
        try {
            new TerminalDemo().execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void execute() throws IOException {
        Process p = new ProcessBuilder().redirectErrorStream(true).command(cmd).start();
        new Thread(new TerminalReader(p)).start();
        new Thread(new TerminalWriter(p, System.in)).start();
    }

    private static class TerminalWriter implements Runnable {
        private final OutputStream os;
        private final BufferedReader bisr;
        private final Process process;

        public TerminalWriter(Process process, InputStream is) {
            this.process = process;
            this.os = process.getOutputStream();
            this.bisr = new BufferedReader(new InputStreamReader(is));
        }


        @Override
        public void run() {
            String s;
            try {
                while (true) {
                    if ((s = bisr.readLine()) == null) {
                        break;
                    }
                    os.write(s.getBytes());
                    os.write("\n".getBytes());
                    os.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                process.destroy();
            }
        }
    }

    private static class TerminalReader implements Runnable {
        private final BufferedReader br;
        private final Process process;

        public TerminalReader(Process process) {
            this.process = process;
            this.br = new BufferedReader(new InputStreamReader(process.getInputStream()));
        }

        @Override
        public void run() {
            String s;
            try {
                while (true) {
                    if ((s = br.readLine()) == null) {
                        break;
                    }
                    System.out.println(s);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                process.destroy();
            }
        }
    }
}